package com.wosai.teach.fragment;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wosai.teach.R;
import com.wosai.teach.activity.MainActivity;
import com.wosai.teach.adapter.SimulationAdapter;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.ExpDateRel;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.entity.GridInfo;
import com.wosai.teach.listener.SimuOnItemClickListener;
import com.wosai.teach.service.DownLoadFactory;
import com.wosai.teach.service.DownLoadService;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.AppUtil;
import com.wosai.teach.utils.ListViewUtils;
import com.wosai.teach.utils.OtherUtils;
import com.wosai.teach.utils.SynchUtils;

public class SimulationFragment extends AppFragment {
	private View view;

	private GridView myGrid;

	private GridView unGrid;

	private LinearLayout myLL;

	private LinearLayout unLL;

	private List<GridInfo> unList = new ArrayList<GridInfo>();

	private List<GridInfo> myList = new ArrayList<GridInfo>();

	private SimuOnItemClickListener listener;

	private NewProgressDialog progressdialog;

	private SimulationAdapter myAdapter;

	private SimulationAdapter unAdapter;

	private DownLoadFactory factory;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.frag_simulation, container, false);
		init();
		initView();
		loadSoftInfo();
		return view;
	}

	private void initView() {
		((MainActivity) getActivity()).setTopTitle("中策仿真");
		factory = DownLoadService.getDownLoadManager(getActivity()
				.getApplicationContext());
		listener = new SimuOnItemClickListener(getActivity(), db, factory, this);

		myGrid = (GridView) view.findViewById(R.id.gv_simu_my);
		unGrid = (GridView) view.findViewById(R.id.gv_simu_un);
		myLL = (LinearLayout) view.findViewById(R.id.simu_ll_my);
		unLL = (LinearLayout) view.findViewById(R.id.simu_ll_un);
		myLL.setVisibility(View.GONE);
		unLL.setVisibility(View.GONE);

		myAdapter = new SimulationAdapter(getActivity(),
				new ArrayList<GridInfo>(), db, listener);
		myGrid.setAdapter(myAdapter);

		unAdapter = new SimulationAdapter(getActivity(),
				new ArrayList<GridInfo>(), db, listener);
		unGrid.setAdapter(unAdapter);
		unGrid.setOnItemClickListener(listener);
		myGrid.setOnItemClickListener(listener);
	}

	private void loadSoftInfo() {
		progressdialog = NewProgressDialog.showProgress(getActivity(),
				"努力加载中...", false);
		String url = C.HTTP_URL_EXPERIMENT_LIST;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							JSONObject jsonObject = JSON.parseObject(result
									.getObject().toString());
							List<Experiment> expList = JSON.parseArray(
									jsonObject.getString("experimentList"),
									Experiment.class);
							db.deleteAll(Selector.from(Experiment.class));
							db.saveAll(expList);
							callResult(true);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						callResult(false);
					}
				});
	}

	public void callResult(boolean success) {
		List<Experiment> expList = db.findAll(Selector.from(Experiment.class));
		if (OtherUtils.CheckNull(expList)) {
			// 没有数据
			if (success) {
				unAdapter.setObjList(new ArrayList<GridInfo>());
				myAdapter.setObjList(new ArrayList<GridInfo>());
			}
		} else {
			unList = new ArrayList<GridInfo>();
			myList = new ArrayList<GridInfo>();
			for (Experiment exp : expList) {
				GridInfo grid = new GridInfo();
				grid.setName(exp.getExpName());
				grid.setImage(exp.getPicURL1());
				grid.setRelId(exp.getExpId() + "");
				grid.setOtherDesc(exp.getHotCount());
				PackageInfo pi = AppUtil
						.getPackageInfo(exp.getApkPackageName());
				int ver = AppUtil.getVersionCode(pi);
				if (ver > 0) {
					myList.add(grid);
				} else {
					unList.add(grid);
				}
				ExpDateRel rel = db.findFirst(Selector.from(ExpDateRel.class)
						.where("expId", "=", exp.getExpId()));
				if (rel == null) {
					rel = new ExpDateRel();
					rel.setCreateDate(new Date().getTime());
					rel.setExpId(exp.getExpId() + "");
					db.save(rel);
				}
			}
			myList = modifyMyList(myList);
			unAdapter.setObjList(unList);
			myAdapter.setObjList(myList);
			if (!OtherUtils.CheckNull(myList)) {
				myLL.setVisibility(View.VISIBLE);
			} else {
				myLL.setVisibility(View.GONE);
			}
			if (!OtherUtils.CheckNull(unList)) {
				unLL.setVisibility(View.VISIBLE);
			} else {
				unLL.setVisibility(View.GONE);
			}
		}
		unAdapter.notifyDataSetChanged();
		myAdapter.notifyDataSetChanged();
		ListViewUtils.setGridViewHeightBasedOnChildren(unGrid);
		ListViewUtils.setGridViewHeightBasedOnChildren(myGrid);
		if (progressdialog != null) {
			progressdialog.dismiss();
		}
	}

	public void downloadApk(int expId) {
		int local = 0;
		for (int i = 0; i < unList.size(); i++) {
			GridInfo gi = (GridInfo) unList.get(i);
			if (gi.getRelId().equals(expId + "")) {
				local = i;
				break;
			}
		}

		this.unGrid.performItemClick(unGrid.getChildAt(local),
				local, this.unAdapter.getItemId(local));
		
		
	}

	/**
	 * 把最近打开的两个实验放到前面
	 * 
	 * @param myList
	 * @return
	 */
	public List<GridInfo> modifyMyList(List<GridInfo> myList) {
		List<GridInfo> resultList = new ArrayList<GridInfo>();
		List<GridInfo> beforeList = new ArrayList<GridInfo>();
		if (OtherUtils.CheckNull(myList)) {
			return resultList;
		}
		List<ExpDateRel> edList = db.findAll(Selector.from(ExpDateRel.class)
				.orderBy("updateDate", true));
		if (OtherUtils.CheckNull(edList)) {
			return resultList;
		}
		int before = 0, max = 2;
		for (ExpDateRel ed : edList) {
			for (GridInfo gi : myList) {
				if (ed.getExpId().equals(gi.getRelId())) {
					myList.remove(gi);
					beforeList.add(gi);
					if (++before >= max) {
						resultList.addAll(beforeList);
						resultList.addAll(myList);
						return resultList;
					} else {
						break;
					}
				}
			}
		}
		resultList.addAll(beforeList);
		resultList.addAll(myList);
		return resultList;
	}

	/**
	 * 回到顶部
	 */
	public void gotoTop() {
		view.scrollTo(0, 0);
	}

	@Override
	public void onResume() {
		super.onResume();
		if (AppGlobal.simulationRefresh) {
			AppGlobal.simulationRefresh = false;
			callResult(true);
			gotoTop();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.REQUEST_CODE_EXP_DETAIL
				|| requestCode == C.REQUEST_CODE_INSTALL
				|| requestCode == C.REQUEST_CODE_UNINSTALL) {
			callResult(true);
			gotoTop();
		}
		if (requestCode == C.REQUEST_CODE_OPEN_SOFT) {
			SynchUtils.initLastOpenTime();
		}
	}

}
